<!--
 * @Description: 预约单创建
 * @Autor: 何兴家
 * @Date: 2020-07-20 18:59:35
 * @LastEditors: 马毅
 * @LastEditTime: 2021-12-30 14:08:42
-->

<template>
  <div>
    <FormPanel v-loading="orderIsLoading" ref="mainForm" style="margin-top: 15px" :list="mainFromList" :cols="4" :labelWidth="100" :isSubmitBtn="false"></FormPanel>
    <FormPanel ref="repairTypeFrom" :list="repairTypeFromList" :cols="4" :labelWidth="100" :isSubmitBtn="false"></FormPanel>
    <ButtonArea :containerStyle="{ paddingLeft: '100px' }">
      <el-button type="primary" @click="handlePrecontractStatusBtnClick">预约情况</el-button>
      <el-button type="primary" :disabled="btnDisabled" @click="handleMonitorBtnClick">监控信息</el-button>
      <el-button type="primary" :disabled="btnDisabled" @click="handleComplainHistoryClick">客诉历史</el-button>
      <el-button type="primary" :disabled="btnDisabled" @click="handleUseRepairSuggestClick">导入维修建议</el-button>
      <el-button type="primary" :disabled="btnDisabled" @click="handleRepairSetMealBtnClick">维修组合</el-button>
    </ButtonArea>
    <el-tabs v-model="activeTab">
      <el-tab-pane label="预约项目" :name="'pro'">
        <FilterTable
          ref="repairProTable"
          columnsRef="repair_repairReception_precontractArrange_repairPro"
          height="auto"
          :dataSource="repairLabourList"
          :columns="repairProColumns"
          :onColumnsChange="columns => (this.repairProColumns = columns)"
          :onSyncTableData="handleLabourTableChange"
          :onRowSelectChange="handleLabourTableSelect"
        >
          <template slot="controls">
            <el-button size="small" type="primary" icon="el-icon-plus" :disabled="btnDisabled" @click="handleAddRepairLabourBtnClick">新增预约项目</el-button>
            <el-button size="small" type="danger" :disabled="btnDisabled" @click="handleDeleteRepairLabour">删除</el-button>
          </template>
        </FilterTable>
      </el-tab-pane>
      <el-tab-pane label="预约配件" :name="'part'">
        <FilterTable
          ref="repairPartTable"
          columnsRef="repair_repairReception_precontractArrange_repairPart"
          height="auto"
          :dataSource="repairPartList"
          :columns="repairPartColumns"
          :onColumnsChange="columns => (this.repairPartColumns = columns)"
          :onCellChange="handlePartTableCellChange"
          :onSyncTableData="handlePartTableChange"
          :onRowSelectChange="handlePartTableSelect"
        >
          <template slot="controls">
            <el-button size="small" type="primary" icon="el-icon-plus" :disabled="btnDisabled" @click="handleAddRepairPartBtnClick">新增预约配件</el-button>
            <el-button size="small" type="danger" :disabled="btnDisabled" @click="handleDeleteRepairPart">删除</el-button>
          </template>
        </FilterTable>
      </el-tab-pane>
    </el-tabs>
    <FormPanel style="margin-top: 15px" ref="totalAmountForm" :list="totalAmountFormList" :isSubmitBtn="false"></FormPanel>
    <div :class="isBottomBtn ? 'btnWrap' : ''" :style="{ display: 'flex', justifyContent: 'center' }">
      <AjaxButton type="primary" :disabled="btnDisabled" :click="handleSaveBtnClick" v-if="openType !== 'detail'">确 定</AjaxButton>
      <AjaxButton type="primary" :disabled="btnDisabled" v-if="openType === 'edit' && appid == 'beijing'" :click="handleCancelBookingOrder">取消预约</AjaxButton>
      <!-- <el-button type="primary" :disabled="btnDisabled && pageType != 'detail'">打印单据</el-button> -->
      <printBookingOrder style="margin-left: 10px" :orderNo="pageBookingOrderNo" :disabled="btnDisabled && pageType != 'detail'" />
      <el-button type="primary" :disabled="btnDisabled && pageType != 'detail'" @click="handleResetPage">取 消</el-button>
    </div>

    <!-- 车辆选择 -->
    <BaseDialog :visible.sync="showVehicleChoicePanel" title="车辆选择" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <vehicleChoice @close="showVehicleChoicePanel = false" @onConfirm="handleVehicleChoiceConfirm" />
    </BaseDialog>

    <!-- 预约时间段选择 -->
    <BaseDialog :visible.sync="showAppointmentTimeChoicePanel" title="预约限量" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <appointmentTimeChoice :defaultDate="bookingComeTime" @close="showAppointmentTimeChoicePanel = false" @onConfirm="handleAppointmentTimeChoiceConfirm" />
    </BaseDialog>

    <!-- 维修项目新增 -->
    <BaseDialog :visible.sync="showRepairLabourAddPanel" title="预约新增项目" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <addRepairLabour :modelId="carModelId" @close="showRepairLabourAddPanel = false" @onConfirm="handleRepairLabourAddConfirm" />
    </BaseDialog>

    <!-- 维修配件新增 -->
    <BaseDialog :visible.sync="showRepairPartAddPanel" title="预约新增配件" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <selectPart :powerType="carPowerType" @close="showRepairPartAddPanel = false" @onConfirm="handleRepairPartAddConfirm" />
    </BaseDialog>

    <!-- 客诉历史 -->
    <BaseDialog :visible.sync="showComplainHistoryPanel" title="客诉历史" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <complainHistory :vin="carVin" @close="showComplainHistoryPanel = false" />
    </BaseDialog>

    <!-- 维修建议 -->
    <BaseDialog :visible.sync="showRepairSuggestPanel" title="维修建议" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <repairSuggest @close="showRepairSuggestPanel = false" />
    </BaseDialog>

    <!-- 维修组合(套餐) -->
    <BaseDialog :visible.sync="showRepairSetMealPanel" title="维修套餐信息" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <repairSetMeal :powerType="carPowerType" :selectedSetMealCodeList="selectedSetMealCodeList" @close="showRepairSetMealPanel = false" @onConfirm="handleSetMealConfirm" />
    </BaseDialog>

    <!-- 取消预约 -->
    <BaseDialog :visible.sync="showCancelPanel" title="取消预约" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <cancelBookingOrder @close="showCancelPanel = false" @refesh="refeshTableData" :bookingOrderNo="defaultBookingOrderNo" />
    </BaseDialog>

    <!-- 监控信息 -->
    <BaseDialog :visible.sync="showMonitorMessagePanel" title="监控信息" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <monitorMessage :vin="carVin" :carInfo="carInfoObj" :openType="'bookingOrder'" @close="showMonitorMessagePanel = false" />
    </BaseDialog>

    <!-- 预约情况 -->
    <BaseDialog :visible.sync="showPrecontractStatusPanel" title="预约情况查询" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <precontractStatus @close="showPrecontractStatusPanel = false" />
    </BaseDialog>
  </div>
</template>

<script>
import { dictionary } from '@/utils/dictMixin';
import { confirmAction, notifyAction, jsonToHump, findFormItem, findTableItem } from '@/utils';
import dictCode from '@/utils/dictCode';
import _ from 'lodash';

import addRepairLabour from './addRepairLabour';
import selectPart from './selectPart';
import complainHistory from './complainHistory';
import repairSuggest from './repairSuggest';
import vehicleChoice from './vehicleChoice';
import appointmentTimeChoice from './appointmentTimeChoice';
import cancelBookingOrder from '../precontractStatus/cancelBookingOrder';
import repairSetMeal from '../customer/repairSetMeal';
import monitorMessage from '../customer/monitorMessage';
import precontractStatus from './precontractStatus';
import printBookingOrder from './printBookingOrder';

import { searchRoleByCode, searchRoleByCodes } from '@/api/common/empSelect/index';
import { savePrecontractOrder, queryLabourPartsByBookingNo } from '@/api/repair/repairReception/precontractArrange';
import { queryPrecontractOrder } from '@/api/repair/repairReception/precontractStatus';
import { getPinpSelect, getChexSelect, queryModelBySeriesId } from '@/api/repair/repairReception/customer/brand';
import { getAppId } from '@/assets/js/auth';

export default {
  props: ['defaultPageType', 'defaultBookingOrderNo', 'defaultData'],
  mixins: [dictionary],
  components: {
    addRepairLabour,
    selectPart,
    complainHistory,
    repairSuggest,
    vehicleChoice,
    appointmentTimeChoice,
    cancelBookingOrder,
    repairSetMeal,
    monitorMessage,
    precontractStatus,
    printBookingOrder
  },
  data() {
    this.deletedRepairLabourList = []; // 删除的维修项目
    this.deletedRepairPartList = []; // 删除的维修配件
    this.selectedRepairLabourList = []; // 选中的维修项目数据
    this.selectedRepairPartList = []; // 选中的维修配件数据
    this.carPowerType = 60081001; // 所选车辆动力类型
    this.carInfoObj = {}; // 车辆信息对象

    return {
      pageType: 'default', // 页面状态 default create edit detail
      mainFromList: this.createMainFormList(),
      repairTypeFromList: this.createCheckFormList(),
      totalAmountFormList: this.createTotalAmountList(),
      repairProColumns: this.createRepairProColumns(),
      repairPartColumns: this.createRepairPartColumns(),
      activeTab: 'pro',
      appid: getAppId(),
      orderIsLoading: false, // 订单详情是否在请求
      repairLabourList: [], // 维修项目列表（初始化）
      repairPartList: [], // 维修配件列表（初始化）
      syncRepairLabourList: [], // 同步的维修项目
      syncRepairPartList: [], // 同步的维修配件
      showRepairLabourAddPanel: false, // 是否显示添加维修项目弹窗
      showRepairPartAddPanel: false, // 是否显示添加维修配件弹窗
      showRepairPartAddPanel: false, // 是否显示配件添加弹窗
      showComplainHistoryPanel: false, // 是否显示客诉历史弹窗
      showRepairSuggestPanel: false, // 是否显示建议维修项目弹窗
      showVehicleChoicePanel: false, // 是否显示车辆选择弹窗
      showRepairSetMealPanel: false, // 是否显示维修套餐弹窗
      showAppointmentTimeChoicePanel: false, // 是否显示预约限量弹窗
      showCancelPanel: false, // 是否显示取消预约弹窗
      showMonitorMessagePanel: false, // 是否显示监控信息弹窗
      showPrecontractStatusPanel: false // 是否显示预约状况查询弹窗
    };
  },
  computed: {
    btnDisabled() {
      return this.orderIsLoading || this.pageType === 'default' || this.pageType == 'detail';
    },
    bookingComeTime() {
      return this.mainFromList.find(item => item.fieldName === 'bookingComeTime').initialValue;
    },
    isBottomBtn() {
      return !!this.defaultPageType;
    },
    // 其他页面打开时页面类型
    openType() {
      return this.defaultPageType;
    },
    // 维修项目字典项(供配件使用)
    repairLabourDicts() {
      return this.syncRepairLabourList.map(item => ({ text: item.LABOUR_NAME, value: item.LABOUR_CODE }));
    },
    // 已选的套餐代码（通过项目配件过滤）
    selectedSetMealCodeList() {
      return [...new Set([...this.syncRepairLabourList.map(item => item.PACKAGE_CODE), ...this.syncRepairPartList.map(item => item.PACKAGE_CODE)])];
    },
    // 车型id（用于查询车型对应维修项目）
    carModelId() {
      return findFormItem(this.mainFromList, 'model').initialValue;
    },
    // 车辆vin
    carVin() {
      return findFormItem(this.mainFromList, 'vin').initialValue;
    },
    // 预约单号
    pageBookingOrderNo() {
      return findFormItem(this.mainFromList, 'bookingOrderNo').initialValue;
    }
  },
  watch: {
    // 监听页面状态调整字段禁用
    pageType(newVal, oldVal) {
      this.setFormDisabledStatus(newVal);
    },
    repairLabourDicts(newVal, oldVal) {
      findTableItem(this.repairPartColumns, 'LABOUR_CODE').editItems = findTableItem(this.repairPartColumns, 'LABOUR_CODE').filterItems = newVal;
    }
  },
  mounted() {
    this.queryServiceConsultantList();
    this.queryRepairTechnician();
    this.queryBrandDicts();
    // 其他页面进入初始化数据
    this.defaultPageType && (this.pageType = this.defaultPageType);
    this.defaultBookingOrderNo && this.initOrderData(this.defaultBookingOrderNo);
    this.defaultData && this.initDefaultData();
  },
  methods: {
    createMainFormList() {
      return [
        {
          type: 'INPUT',
          label: '预约单号',
          fieldName: 'bookingOrderNo',
          initialValue: '',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '车牌号',
          fieldName: 'license',
          initialValue: '',
          unitRender: () => {
            return (
              <el-button
                icon="el-icon-search"
                onClick={() => {
                  this.showVehicleChoicePanel = true;
                }}
              />
            );
          }
        },
        {
          type: 'INPUT',
          label: 'VIN',
          fieldName: 'vin',
          readonly: false,
          disabled: true,
          unitRender: () => {
            return <el-button icon="el-icon-warning" />;
          }
        },
        {
          type: 'INPUT',
          label: '预约进厂日期',
          fieldName: 'bookingComeTime',
          placeholder: '请选择...',
          readonly: true,
          disabled: true,
          unitRender: () => {
            return (
              <el-button
                icon="el-icon-warning"
                onClick={() => {
                  this.showAppointmentTimeChoicePanel = true;
                }}
              />
            );
          },
          rules: [{ required: true, message: '请输入预约进场时间', trigger: 'change' }]
        },
        {
          type: 'INPUT',
          label: '车主',
          fieldName: 'ownerName',
          disabled: true,
          placeholder: '请选择...',
          unitRender: () => {
            return <el-button icon="el-icon-warning" />;
          }
        },
        {
          type: 'INPUT',
          label: '联系人',
          fieldName: 'contactorName',
          placeholder: '请输入...',
          disabled: true,
          rules: [{ required: true, message: '请输入联系人', trigger: 'blur' }]
        },
        {
          type: 'INPUT',
          label: '联系人电话',
          fieldName: 'contactorPhone',
          placeholder: '请输入...',
          disabled: true,
          itemList: []
        },
        {
          type: 'INPUT',
          label: '联系人手机',
          fieldName: 'contactorMobile',
          placeholder: '请输入...',
          maxlength: 11,
          disabled: true,
          rules: [{ required: true, validator: this.checkPhone, trigger: 'blur', message: '请输入联系人手机' }]
        },
        {
          type: 'SELECT',
          label: '预约顾问',
          fieldName: 'serviceAdvisor',
          placeholder: '请选择...',
          filterable: true,
          disabled: true,
          // rules: [{ required: true, message: '请选择服务顾问', trigger: 'change' }],
          itemList: []
        },
        {
          type: 'SELECT',
          label: '品牌',
          fieldName: 'brand',
          placeholder: '请选择...',
          disabled: true,
          itemList: [],
          change: val => {
            // this.changePinpSelect(val);
          },
          initialValue: ''
        },
        {
          type: 'SELECT',
          label: '车系',
          fieldName: 'series',
          placeholder: '请选择...',
          disabled: true,
          itemList: [],
          change: val => {
            // this.changeChexSelect(val);
          },
          initialValue: ''
        },
        {
          type: 'SELECT',
          label: '车型',
          fieldName: 'model',
          placeholder: '请选择...',
          disabled: true,
          itemList: [],
          initialValue: ''
        },
        {
          type: 'SELECT',
          label: '指定技师',
          fieldName: 'chiefTechnician',
          placeholder: '请选择...',
          disabled: true,
          itemList: []
        },
        {
          type: 'SELECT',
          label: '预约类别',
          fieldName: 'bookingTypeCode',
          placeholder: '请选择...',
          itemList: [
            { text: '客户预约', value: '80551001' },
            { text: '被动预约', value: '80551002' }
          ],
          disabled: true
          // rules: [{ required: true, message: '请输入预约类别', trigger: 'change' }]
        },
        {
          type: 'SELECT',
          label: '预约来源',
          fieldName: 'bookingSource',
          placeholder: '请选择...',
          disabled: true,
          initialValue: 80101001,
          itemList: this.createDictList('1019')
        },
        {
          type: 'INPUT',
          label: '预估金额',
          fieldName: 'estimateAmount',
          precision: 2,
          disabled: true
        },
        {
          type: 'SELECT',
          label: '预约状态',
          fieldName: 'bookingOrderStatus',
          placeholder: '请选择...',
          disabled: true,
          itemList: this.createDictList(8067)
        },
        {
          type: 'INPUT',
          label: '客户描述',
          fieldName: 'customerDesc',
          selfCols: 2,
          disabled: true
        },
        {
          type: 'CHECKBOX',
          label: '缺料预约',
          fieldName: 'isLackPart',
          initialValue: 10041002,
          disabled: true,
          options: {
            trueValue: 10041001,
            falseValue: 10041002
          }
        },
        {
          type: 'INPUT',
          label: '备注',
          fieldName: 'remark',
          disabled: true,
          selfCols: 2,
          onInput: (e, e2) => {
            console.log(e, e2);
          }
        }
      ];
    },
    createCheckFormList() {
      return [
        {
          type: 'MULTIPLE_CHECKBOX',
          label: '',
          fieldName: 'repairTypes',
          disabled: true,
          selfCols: 4,
          itemList: [
            { text: '保养', value: 'maintain' },
            { text: '维修', value: 'repair' },
            { text: '漆面修复', value: 'paintRepair' },
            { text: '异响', value: 'abnormalSound' },
            { text: '轮胎损伤', value: 'tireDamage' },
            { text: '空调异常', value: 'abnormalAirConditioning' },
            { text: '车机软件', value: 'vehicleSoftware' },
            { text: '其他', value: 'other' }
          ]
        }
      ];
    },
    createTotalAmountList() {
      return [
        {
          type: 'INPUT',
          label: '预估金额',
          fieldName: 'allAmount',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '预估工时费',
          fieldName: 'labourAmount',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '预估配件费',
          fieldName: 'partSalesAmount',
          disabled: true
        }
      ];
    },
    createRepairProColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.$index + 1}</span>;
          }
        },
        {
          title: '维修项目代码',
          dataIndex: 'LABOUR_CODE',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '维修项目名称',
          dataIndex: 'LABOUR_NAME',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '标准工时',
          dataIndex: 'STD_LABOUR_HOUR',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '工时费',
          dataIndex: 'LABOUR_AMOUNT',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '工时单价',
          dataIndex: 'LABOUR_PRICE',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '组合代码',
          dataIndex: 'PACKAGE_CODE',
          sorter: true,
          filter: true,
          filterType: 'input'
        }
      ];
    },
    createRepairPartColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.$index + 1}</span>;
          }
        },
        {
          title: '仓库',
          dataIndex: 'STORAGE_CODE',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: []
        },
        {
          title: '配件代码',
          dataIndex: 'PART_NO',
          sorter: true,
          filter: true,
          showOverflowTooltip: true,
          filterType: 'input'
        },
        {
          title: '配件名称',
          dataIndex: 'PART_NAME',
          sorter: true,
          filter: true,
          showOverflowTooltip: true,
          filterType: 'input'
        },
        {
          title: '预约数量',
          dataIndex: 'BOOKING_QUANTITY',
          sorter: true,
          filter: true,
          filterType: 'number',
          editType: 'text',
          editable: true,
          defaultEditable: true
        },
        {
          title: '维修项目名称',
          dataIndex: 'LABOUR_CODE',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: [],
          editable: true,
          defaultEditable: true,
          editType: 'select',
          editItems: []
        },
        {
          title: '预留',
          dataIndex: 'IS_OBLIGATED',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('1004'),
          editable: true,
          defaultEditable: true,
          editType: 'select',
          editItems: this.createDictList('1004')
        },
        {
          title: '是否预收款',
          dataIndex: 'IS_PAYMENT',
          editable: true,
          defaultEditable: true,
          editType: 'checkbox',
          editItems: [
            { trueValue: 10041001, text: '' },
            { falseValue: 10041002, text: '' }
          ]
        },
        {
          title: '组合代码',
          dataIndex: 'PACKAGE_CODE',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '配件销售金额',
          dataIndex: 'PART_AMOUNT',
          sorter: true,
          filter: true,
          filterType: 'number'
        },
        {
          title: '配件销售单价',
          dataIndex: 'SALES_PRICE',
          sorter: true,
          filter: true,
          filterType: 'number'
        }
      ];
    },
    // 获取服务顾问列表
    async queryServiceConsultantList() {
      let serviceConsultant = { role: dictCode.SERVICE_CONSULTANT };
      let res = await searchRoleByCode(serviceConsultant);
      if (res.resultCode == 200) {
        this.mainFromList.find(item => item.fieldName === 'serviceAdvisor').itemList = res.data.map(item => ({
          text: item.employeeName,
          value: item.userId + ''
        }));
      }
      console.log(res, 'hexj001');
    },
    // 获取指定技师列表
    async queryRepairTechnician() {
      let technician = { role: dictCode.TECHNICIAN }; // 指定技师
      let res = await searchRoleByCodes(technician);
      if (res.resultCode == 200) {
        findFormItem(this.mainFromList, 'chiefTechnician').itemList = res.data.map(item => ({
          text: item.employeeName,
          value: item.userId + ''
        }));
      }
    },
    // 车辆选择带回
    handleVehicleChoiceConfirm(e) {
      let vehicleData = _.cloneDeep(e);
      jsonToHump(vehicleData);
      this.carInfoObj = vehicleData;
      this.mainFromList.forEach(item => {
        item.initialValue = _.isNil(vehicleData[item.fieldName]) ? '' : vehicleData[item.fieldName];
      });
      this.querySeriesModelDicts(vehicleData.brand, vehicleData.series);
      this.carPowerType = vehicleData.powerType; // 车辆动力类型单独存放(用于配件添加的选择)
      this.showVehicleChoicePanel = false;
      this.pageType = 'create';

      // 赋值预约来源默认值
      findFormItem(this.mainFromList, 'bookingSource').initialValue = 10191001;

      this.$nextTick(() => {
        this.handleMonitorBtnClick();
      });
    },
    // 初始化部分默认数据
    initDefaultData() {
      this.mainFromList.forEach(item => {
        this.defaultData[item.fieldName] && (item.initialValue = this.defaultData[item.fieldName]);
      });
    },
    // 预约限量选择返回
    handleAppointmentTimeChoiceConfirm(e) {
      this.mainFromList.find(item => item.fieldName === 'bookingComeTime').initialValue = e;
      this.showAppointmentTimeChoicePanel = false;
    },
    // 点击客诉历史按钮
    handleComplainHistoryClick() {
      this.showComplainHistoryPanel = true;
    },
    // 点击导入维修建议
    handleUseRepairSuggestClick() {
      this.showRepairSuggestPanel = true;
    },
    // 点击维修组合(套餐)
    handleRepairSetMealBtnClick() {
      this.showRepairSetMealPanel = true;
    },
    // 点击监控信息按钮
    handleMonitorBtnClick() {
      this.showMonitorMessagePanel = true;
    },
    // 点击预约情况
    handlePrecontractStatusBtnClick() {
      this.showPrecontractStatusPanel = true;
    },
    // 同步维修项目table数据
    handleLabourTableChange(list) {
      this.syncRepairLabourList = list;
      this.calcTotalAmount();
    },
    // 同步维修配件table数据
    handlePartTableChange(list) {
      this.syncRepairPartList = list;
      this.calcTotalAmount();
    },
    // 维修配件表格可编辑数据改变
    handlePartTableCellChange(data, row) {
      let keys = Object.keys(data);
      let dataIndex = keys[0].split('|')[1];
      if (dataIndex === 'BOOKING_QUANTITY') {
        row.PART_AMOUNT = row.BOOKING_QUANTITY * row.SALES_PRICE;
        this.calcTotalAmount();
      }
    },
    // 维修项目选中
    handleLabourTableSelect(list) {
      this.selectedRepairLabourList = list;
    },
    // 维修配件选中
    handlePartTableSelect(list) {
      this.selectedRepairPartList = list;
    },
    // 删除维修项目
    handleDeleteRepairLabour() {
      if (!this.selectedRepairLabourList.length) return notifyAction('请选择需要删除的行项', 'warning');
      confirmAction('是否确认删除所选项目？', 'warning')
        .then(res => {
          this.$refs.repairProTable.EXECUTE_DELETE(this.selectedRepairLabourList);
          this.selectedRepairLabourList.forEach(item => {
            item.ITEM_ID && this.deletedRepairLabourList.push(item);
          });
          this.selectedRepairLabourList = [];
          notifyAction('删除成功', 'success');
        })
        .catch(err => {});
    },
    // 删除维修配件
    handleDeleteRepairPart() {
      if (!this.selectedRepairPartList.length) return notifyAction('请选择需要删除的行项', 'warning');
      confirmAction('是否确认删除所选配件？', 'warning')
        .then(res => {
          this.$refs.repairPartTable.EXECUTE_DELETE(this.selectedRepairPartList);
          this.selectedRepairPartList.forEach(item => {
            item.ITEM_ID && this.deletedRepairPartList.push(item);
          });
          this.selectedRepairPartList = [];
          notifyAction('删除成功', 'success');
        })
        .catch(err => {});
    },
    // 点击新增维修项目
    handleAddRepairLabourBtnClick() {
      this.showRepairLabourAddPanel = true;
    },
    // 点击新增配件
    handleAddRepairPartBtnClick() {
      if (!this.selectedRepairLabourList.length) return notifyAction('请先选择对应维修项目', 'warning');
      this.showRepairPartAddPanel = true;
    },
    // 维修组合带回事件
    handleSetMealConfirm(e) {
      console.log(e);
      if (e.labourList.length) {
        e.labourList.forEach(item => {
          item.LABOUR_PRICE = 120;
          item.LABOUR_AMOUNT = item.LABOUR_PRICE * item.STD_LABOUR_HOUR;
        });
        this.$refs.repairProTable.EXECUTE_INSERT(e.labourList);
      }
      if (e.partList.length) {
        let dataClone = _.cloneDeep(e.partList);
        this.initPartData(dataClone);
        this.$refs.repairPartTable.EXECUTE_INSERT(dataClone);
      }
    },
    // 维修项目新增带回项目事件
    handleRepairLabourAddConfirm(e) {
      console.log(e, 'hexj001');
      if (this.syncRepairLabourList.find(item => item.LABOUR_CODE == e.LABOUR_CODE)) return notifyAction(`维修项目：${e.LABOUR_CODE}，已存在不能重复插入`, 'warning');
      this.$refs.repairProTable.EXECUTE_INSERT(e);
      this.showRepairLabourAddPanel = false;
    },
    // 维修配件新增配件带回事件
    handleRepairPartAddConfirm(e) {
      // SALES_PRICE 销售价 BOOKING_QUANTITY 数量
      let dataClone = _.cloneDeep(e);
      this.initPartData([dataClone]);
      this.$refs.repairPartTable.EXECUTE_INSERT(dataClone);
      this.showRepairPartAddPanel = false;
    },
    // 插入前初始化配件数据
    initPartData(list) {
      list.forEach(item => {
        item.SALES_PRICE = item.SALES_PRICE || item.PART_SALES_PRICE || 0;
        item.BOOKING_QUANTITY = item.BOOKING_QUANTITY || item.PART_QUANTITY || 1;
        item.PART_AMOUNT = item.BOOKING_QUANTITY * item.SALES_PRICE;
        item.LABOUR_CODE = this.selectedRepairLabourList.length ? this.selectedRepairLabourList[0].LABOUR_CODE : '';
      });
    },
    // 计算预估金额
    calcTotalAmount() {
      let totalRepairLabourAmount = 0, // 预估工时金额
        totalRepairPartAmount = 0; // 预估配件金额

      // 计算项目费用
      this.syncRepairLabourList.forEach(item => {
        totalRepairLabourAmount += +item.LABOUR_AMOUNT || 0;
      });
      // 计算配件费用
      this.syncRepairPartList.forEach(item => {
        totalRepairPartAmount += +item.PART_AMOUNT || 0;
      });

      this.totalAmountFormList.find(item => item.fieldName === 'labourAmount').initialValue = totalRepairLabourAmount;
      this.totalAmountFormList.find(item => item.fieldName === 'partSalesAmount').initialValue = totalRepairPartAmount;
      this.totalAmountFormList.find(item => item.fieldName === 'allAmount').initialValue = this.mainFromList.find(item => item.fieldName === 'estimateAmount').initialValue =
        totalRepairLabourAmount + totalRepairPartAmount;
    },
    // 设置页面字段禁用状态
    setFormDisabledStatus(pageType) {
      let disableType = ['default', 'detail']; // 大部分字段禁用的类型
      let status = disableType.includes(pageType) ? true : false;

      let excludeDisabledDataList = ['bookingOrderNo', 'license', 'estimateAmount']; // 禁用状态不变的字段
      this.mainFromList.map(item => {
        !excludeDisabledDataList.includes(item.fieldName) && (item.disabled = status);
      });
      this.repairTypeFromList.forEach(item => {
        item.disabled = status;
      });
      // 特殊字段单独处理
      if (pageType === 'create') {
        this.mainFromList.find(item => item.fieldName === 'bookingOrderStatus').disabled = true;
      }
      if (pageType === 'edit' || 'detail') {
        this.mainFromList.find(item => item.fieldName === 'license').disabled = true;
        this.mainFromList.find(item => item.fieldName === 'vin').disabled = true;
        this.mainFromList.find(item => item.fieldName === 'bookingOrderStatus').disabled = true;
      }
      if (pageType === 'default') {
        this.mainFromList.find(item => item.fieldName === 'license').disabled = false;
      }
    },
    // 初始化页面数据(编辑，查看详情)
    async initOrderData(bookingOrderNo) {
      this.orderIsLoading = true;
      try {
        let orderDetailRes = await queryPrecontractOrder({ bookingOrderNo });
        if (orderDetailRes.resultCode == 200 && orderDetailRes.data.rows.length) {
          let orderData = orderDetailRes.data.rows[0];
          this.carInfoObj = orderData;
          orderData.serviceAdvisor = orderData.bookServiceAdvisor;
          // 主列表赋值
          this.mainFromList.forEach(item => {
            item.initialValue = orderData[item.fieldName] || '';
          });
          // 处理勾选字段部分
          let specialFieldList = this.repairTypeFromList.find(item => item.fieldName == 'repairTypes').itemList.map(item => item.value);
          let valueArr = [];
          specialFieldList.forEach(item => {
            orderData[item] == 10041001 && valueArr.push(item);
          });
          this.repairTypeFromList.find(item => item.fieldName === 'repairTypes').initialValue = valueArr;

          // 单独处理部分数据
          this.carPowerType = orderDetailRes.data.rows[0].powerType || this.carPowerType;

          // 初始化车型车系
          this.querySeriesModelDicts(orderData.brand, orderData.series);

          // 查询项目及配件信息
          this.queryRepairLabourParts(bookingOrderNo);
        }
      } catch (err) {
        console.log(err, '获取订单详情失败');
        setTimeout(() => {
          this.$emit('close');
        }, 3000);
      } finally {
        this.orderIsLoading = false;
      }
    },
    // 查询品牌列表
    async queryBrandDicts() {
      let res = await getPinpSelect();
      if (res.resultCode == 200) {
        findFormItem(this.mainFromList, 'brand').itemList = res.data.map(item => ({ text: item.brandName, value: item.brandId + '' }));
      }
    },
    // 根据品牌及车型id初始化品牌车系下拉框
    querySeriesModelDicts(brandId, seriesId) {
      !_.isNil(brandId) && this.querySeriesDictByBrandId(brandId);
      !_.isNil(seriesId) && this.queryModelDictsBySeriesId(seriesId);
    },
    // 根据品牌id查询车系
    async querySeriesDictByBrandId(brandId) {
      let res = await getChexSelect(brandId);
      if (res.resultCode == 200) {
        findFormItem(this.mainFromList, 'series').itemList = res.data.map(item => ({ text: item.seriesName, value: item.seriesId + '' }));
      }
    },
    // 根据车系id查询车型
    async queryModelDictsBySeriesId(seriesId) {
      let res = await queryModelBySeriesId({ seriesId });
      if (res.resultCode == 200) {
        findFormItem(this.mainFromList, 'model').itemList = res.data.map(item => ({ text: item.modelName, value: item.modelId + '' }));
      }
    },
    // 根据预约单号查询配件及项目信息
    async queryRepairLabourParts(bookingOrderNo) {
      this.$refs.repairProTable.START_LOADING();
      this.$refs.repairPartTable.START_LOADING();
      try {
        let res = await queryLabourPartsByBookingNo({ bookingOrderNo });
        if (res.resultCode == 200) {
          this.repairLabourList = res.data.labour;
          this.repairPartList = res.data.part;
        }
      } catch (err) {
        console.log(err, '查询维修项目配件失败');
      } finally {
        this.$refs.repairProTable.STOP_LOADING();
        this.$refs.repairPartTable.STOP_LOADING();
      }
    },
    // 点击取消预约
    handleCancelBookingOrder() {
      this.showCancelPanel = true;
    },
    // 取消预约成功事件
    refeshTableData() {
      this.$emit('refesh');
      this.$emit('close');
    },
    // 点击取消(重置页面)
    handleResetPage() {
      this.$refs.mainForm.RESET_FORM();
      this.$refs.repairTypeFrom.RESET_FORM();
      this.$refs.totalAmountForm.RESET_FORM();

      this.repairLabourList = [];
      this.repairPartList = [];
      this.deletedRepairLabourList = [];
      this.deletedRepairPartList = [];

      this.pageType = 'default';

      this.isBottomBtn && this.$emit('close');
    },
    // 点击确定(保存)
    async handleSaveBtnClick() {
      // 校验并处理部分数据
      let mainFormData = await this.$refs.mainForm.GET_FORM_DATA();
      let repairTypeData = await this.$refs.repairTypeFrom.GET_FORM_DATA();
      if (mainFormData[0] || repairTypeData[0]) return notifyAction('请填写必填项', 'warning');

      // 配件维修项目列表数据字段转小写
      let labourList = _.cloneDeep(this.syncRepairLabourList);
      let partList = _.cloneDeep(this.syncRepairPartList);
      let deleteLabourList = _.cloneDeep(this.deletedRepairLabourList);
      let deletePartList = _.cloneDeep(this.deletedRepairPartList);
      jsonToHump(labourList);
      jsonToHump(partList);
      jsonToHump(deleteLabourList);
      jsonToHump(deletePartList);

      // 校验配件是否选择维修项目
      let flag = false;
      partList.forEach(item => {
        !item.labourCode && (flag = true);
      });
      if (flag) {
        notifyAction('存在未维护维修项目的配件，请处理', 'warning');
        return false;
      }

      let dataObj = { ...mainFormData[1], labourList, partList, deleteLabourList, deletePartList }; // 提交数据

      // 预约日期补秒
      dataObj.bookingComeTime = dataObj.bookingComeTime + ':00';

      // 处理维修类型数据
      let repairTypeList = this.repairTypeFromList.find(item => item.fieldName == 'repairTypes').itemList.map(item => item.value);
      repairTypeList.forEach(item => {
        dataObj[item] = repairTypeData[1].repairTypes.includes(item) ? 10041001 : 10041002;
      });

      let res = await savePrecontractOrder(dataObj);
      if (res.resultCode == 200) {
        notifyAction('保存成功', 'success');
        this.$emit('refesh'); // 保存后刷新查询的table页
        this.mainFromList.find(item => item.fieldName === 'bookingOrderNo').initialValue = res.data;
        // 保存成功后重新查询配件及项目列表
        this.deletedRepairLabourList = [];
        this.deletedRepairPartList = [];

        // 重新查询工单信息 2021-05-27 调整为保存成功后清除页面
        // this.initOrderData(res.data);
        // this.pageType = 'edit';
        this.handleResetPage();
      }
    }
  }
};
</script>

<style scoped>
.btnWrap {
  position: absolute;
  left: 0px;
  bottom: 0px;
  right: 0px;
  z-index: 9;
  border-top: 1px solid rgb(233, 233, 233);
  padding: 10px 20px;
  background: rgb(255, 255, 255);
  text-align: right;
}
</style>
